<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="Nuxtjs初学习"><meta name="keywords" content="vue nuxtjs"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>Nuxtjs初学习 | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84"><span class="toc-number">1.</span> <span class="toc-text">目录结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1"><span class="toc-number">2.</span> <span class="toc-text">路由</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%99%AE%E9%80%9A%E8%B7%AF%E7%94%B1"><span class="toc-number">2.1.</span> <span class="toc-text">普通路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8A%A8%E6%80%81%E8%B7%AF%E7%94%B1"><span class="toc-number">2.2.</span> <span class="toc-text">动态路由</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E6%A0%A1%E9%AA%8C"><span class="toc-number">2.2.1.</span> <span class="toc-text">参数校验</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97%E8%B7%AF%E7%94%B1"><span class="toc-number">2.3.</span> <span class="toc-text">嵌套路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%AD%E9%97%B4%E4%BB%B6"><span class="toc-number">2.4.</span> <span class="toc-text">中间件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9C%80%E5%90%8E%E4%B8%80%E4%B8%AA%E7%A4%BA%E4%BE%8B"><span class="toc-number">2.5.</span> <span class="toc-text">最后一个示例</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%86%E5%9B%BE"><span class="toc-number">3.</span> <span class="toc-text">视图</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A8%A1%E6%9D%BF"><span class="toc-number">3.1.</span> <span class="toc-text">模板</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B8%83%E5%B1%80"><span class="toc-number">3.2.</span> <span class="toc-text">布局</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#404%E9%A1%B5%E9%9D%A2"><span class="toc-number">3.3.</span> <span class="toc-text">404页面</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%A1%B5%E9%9D%A2"><span class="toc-number">3.4.</span> <span class="toc-text">页面</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E6%95%B0%E6%8D%AE"><span class="toc-number">4.</span> <span class="toc-text">异步数据</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%8A%E4%B8%8B%E6%96%87%E5%AF%B9%E8%B1%A1"><span class="toc-number">4.1.</span> <span class="toc-text">上下文对象</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8F%92%E4%BB%B6"><span class="toc-number">5.</span> <span class="toc-text">插件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B3%A8%E5%85%A5vue%E5%AE%9E%E4%BE%8B"><span class="toc-number">5.1.</span> <span class="toc-text">注入vue实例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B3%A8%E5%85%A5-context"><span class="toc-number">5.2.</span> <span class="toc-text">注入 context</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97"><span class="toc-number">6.</span> <span class="toc-text">模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#vuex"><span class="toc-number">7.</span> <span class="toc-text">vuex</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#fetch%E6%96%B9%E6%B3%95"><span class="toc-number">7.1.</span> <span class="toc-text">fetch方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B6%E4%BB%96"><span class="toc-number">7.2.</span> <span class="toc-text">其他</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B6%E4%BB%96-1"><span class="toc-number">8.</span> <span class="toc-text">其他</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%91%BD%E4%BB%A4"><span class="toc-number">8.1.</span> <span class="toc-text">命令</span></a></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">Nuxtjs初学习</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2021-01-31</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">4.9k</span><span class="post-meta__separator">|</span><span>阅读时长: 18 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>怎么说啦，学这个主要是为了解决seo的问题，使用服务端渲染，给用户更好的体验</p>
<p><a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/">官网</a></p>
<p><a target="_blank" rel="noopener" href="https://www.jspang.com/detailed?id=37">一位大佬的简单教程</a></p>
<p><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV13Z4y1T74J?p=5&spm_id_from=pageDriver">B站视频教程</a></p>
<img src="https://img2018.cnblogs.com/blog/1158910/201908/1158910-20190818204215037-2038459873.png" alt="生命周期" style="zoom:80%;" />

<p>注意上面的<strong>beforecreated</strong>和<strong>created</strong>两个钩子，这两个钩子既可以跑在服务端，也可以跑在客户端。有一个验证就是，使用console，服务端的会在终端里面打印出来，而客户端的会在浏览器的控制台打印出来</p>
<p>剩下的其他部分就是vue自己的其他生命周期钩子了，如mounted这些</p>
<p>在服务器端的钩子不能访问客户端的对象，如window对象，只能获取到服务器的上下文context</p>
<p><strong>nuxtServerInit</strong> ： 这个初始化方法可自定义。写在这个vuex里面主模块的 store的actions里面，起nuxtServerInit这个名字，服务器在初始化的时候就会自动调用这个函数进行初始化</p>
<h3 id="目录结构"><a href="#目录结构" class="headerlink" title="目录结构"></a>目录结构</h3><p>Nuxt自动生产了项目目录，我们先来一个一个介绍一下。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">|-- .nuxt                            // Nuxt自动生成，临时的用于编辑的文件，build</span><br><span class="line">|-- assets                           // 用于组织未编译的静态资源入LESS、SASS 或 JavaScript</span><br><span class="line">|-- components                       // 用于自己编写的Vue组件，比如滚动组件，日历组件，分页组件</span><br><span class="line">|-- layouts                          // 布局目录，用于组织应用的布局组件，相当于vue里的app.vue文件</span><br><span class="line">|-- middleware                       // 用于存放中间件，相当于路由守卫这种</span><br><span class="line">|-- pages                            // 用于存放写的页面，我们主要的工作区域</span><br><span class="line">|-- plugins                          // 用于存放JavaScript插件的地方</span><br><span class="line">|-- static                           // 用于存放静态资源文件，比如图片</span><br><span class="line">|-- store                            // 用于组织应用的Vuex 状态管理。</span><br><span class="line">|-- .editorconfig                    // 开发工具格式配置</span><br><span class="line">|-- .eslintrc.js                     // ESLint的配置文件，用于检查代码格式</span><br><span class="line">|-- .gitignore                       // 配置git不上传的文件</span><br><span class="line">|-- nuxt.config.json                 // 用于组织Nuxt.js应用的个性化配置，已覆盖默认配置</span><br><span class="line">|-- package-lock.json                // npm自动生成，用于帮助package的统一性设置的，yarn也有相同的操作</span><br><span class="line">|-- package.json                     // npm包管理配置文件</span><br></pre></td></tr></table></figure>



<h3 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h3><p>感觉这里有一些特别，跟普通的vue比没了显式的vue-router的目录和文件，Nuxt.js 会依据 <code>pages</code> 目录中的所有 <code>*.vue</code> 文件生成应用的路由配置。可以在执行<code>nuxt</code>命令后在 <strong>.nuxt</strong> 目录里面的router.js文件里面看见生成的路由</p>
<p>路由可对全部页面使用过渡效果。也可单独对某一个页面使用过渡效果（这个需要使用页面组件的transition属性）</p>
<p>全局的直接在一个css文件里面以page开头写动画效果，然后在nuxt.config.js里面的css属性里面引入，nuxt会自动将这个效果应用到全部的页面切换，这也是nuxt约定式的一个体现</p>
<p>进入和离开的active动画一般写在一起，刚进入的状态和最后退出后的状态一般写在一起</p>
<figure class="highlight css"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* 这里是page页面全局的页面切换动画 */</span></span><br><span class="line"><span class="selector-class">.page-enter-active</span>,</span><br><span class="line"><span class="selector-class">.page-leave-active</span> &#123;</span><br><span class="line">  <span class="attribute">transition</span>: all <span class="number">0.5s</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.page-enter</span>,</span><br><span class="line"><span class="selector-class">.page-leave-to</span> &#123;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">nuxt<span class="selector-class">.config</span><span class="selector-class">.js</span></span><br><span class="line">css: [</span><br><span class="line">    <span class="string">&#x27;element-ui/lib/theme-chalk/index.css&#x27;</span>,</span><br><span class="line">	// 在这里引入</span><br><span class="line">    <span class="string">&#x27;assets/main.css&#x27;</span>,</span><br><span class="line">  ],</span><br></pre></td></tr></table></figure>



<h4 id="普通路由"><a href="#普通路由" class="headerlink" title="普通路由"></a>普通路由</h4><p>假设 <code>pages</code> 的目录结构如下：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">pages/</span><br><span class="line">--| user/</span><br><span class="line">-----| index.vue</span><br><span class="line">-----| one.vue</span><br><span class="line">--| index.vue</span><br></pre></td></tr></table></figure>

<p>那么，Nuxt.js 自动生成的路由配置如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">router: &#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;index&#x27;</span>,</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/index.vue&#x27;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;user&#x27;</span>,</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/user&#x27;</span>, <span class="comment">// index.vue文件就直接对应目录名的路由</span></span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/user/index.vue&#x27;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;user-one&#x27;</span>,</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/user/one&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/user/one.vue&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="动态路由"><a href="#动态路由" class="headerlink" title="动态路由"></a>动态路由</h4><p>即是带参数的路由，需要创建对应的<strong>以下划线作为前缀</strong>的 Vue 文件 或 目录。</p>
<p>目录结构：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">pages/</span><br><span class="line">--| _slug/</span><br><span class="line">-----| comments.vue</span><br><span class="line">-----| index.vue</span><br><span class="line">--| users/</span><br><span class="line">-----| _id.vue</span><br><span class="line">--| index.vue</span><br></pre></td></tr></table></figure>

<p>Nuxt.js 生成对应的路由配置表为：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">router: &#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;index&#x27;</span>,</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/index.vue&#x27;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;users-id&#x27;</span>,</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/users/:id?&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/users/_id.vue&#x27;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;slug&#x27;</span>,</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/:slug&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/_slug/index.vue&#x27;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;slug-comments&#x27;</span>,</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/:slug/comments&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/_slug/comments.vue&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你会发现名称为 <code>users-id</code> 的路由路径带有 <code>:id?</code> 参数，表示该路由是可选的。如果你想将它设置为必选的路由，需要在 <code>users/_id</code> 目录内创建一个 <code>index.vue</code> 文件。</p>
<h5 id="参数校验"><a href="#参数校验" class="headerlink" title="参数校验"></a>参数校验</h5><p>Nuxt.js 可以让你在动态路由组件中定义参数校验方法。</p>
<p>举个例子： <code>pages/users/_id.vue</code></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="function"><span class="title">validate</span>(<span class="params">&#123; params &#125;</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 必须是number类型</span></span><br><span class="line">    <span class="keyword">return</span> <span class="regexp">/^\d+$/</span>.test(params.id)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果校验方法返回的值不为 <code>true</code>或<code>Promise</code>中 resolve 解析为<code>false</code>或抛出 Error ， Nuxt.js 将自动加载显示 404 错误页面或 500 错误页面。</p>
<h4 id="嵌套路由"><a href="#嵌套路由" class="headerlink" title="嵌套路由"></a>嵌套路由</h4><p>可以通过 vue-router 的子路由创建 Nuxt.js 应用的嵌套路由。</p>
<p>创建内嵌子路由，你需要添加一个 Vue 文件，同时添加一个<strong>与该文件同名</strong>的目录用来存放子视图组件。</p>
<p><strong>Warning:</strong> 别忘了在父组件(<code>.vue</code>文件) 内增加 <code>&lt;nuxt-child/&gt;</code> 用于显示子视图内容。</p>
<p>假设文件结构如：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">pages/</span><br><span class="line">--| users/</span><br><span class="line">	 <span class="comment"># 这里就一个动态路由文件即可，不需要多个下划线开头的路由文件，反正最后一个url只会匹配一个动态路由文件</span></span><br><span class="line">-----| _id.vue</span><br><span class="line">-----| index.vue</span><br><span class="line">--| users.vue</span><br></pre></td></tr></table></figure>

<p>Nuxt.js 自动生成的路由配置如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">router: &#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/users&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="string">&#x27;pages/users.vue&#x27;</span>,</span><br><span class="line">      <span class="comment">// 这里就是嵌套路由的了</span></span><br><span class="line">      <span class="attr">children</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">path</span>: <span class="string">&#x27;&#x27;</span>,</span><br><span class="line">          <span class="attr">component</span>: <span class="string">&#x27;pages/users/index.vue&#x27;</span>,</span><br><span class="line">          <span class="attr">name</span>: <span class="string">&#x27;users&#x27;</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="comment">// 这里是动态路由，需要参数的</span></span><br><span class="line">          <span class="attr">path</span>: <span class="string">&#x27;:id&#x27;</span>,</span><br><span class="line">          <span class="attr">component</span>: <span class="string">&#x27;pages/users/_id.vue&#x27;</span>,</span><br><span class="line">          <span class="attr">name</span>: <span class="string">&#x27;users-id&#x27;</span></span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="中间件"><a href="#中间件" class="headerlink" title="中间件"></a>中间件</h4><p>相当于路由守卫 执行顺序为nuxt.config.js     layout    pages    （如果都使用了middleware的话）</p>
<p>每一个中间件应放置在 <code>middleware/</code> 目录。文件名的名称将成为中间件名称 (<code>middleware/auth.js</code>将成为 <code>auth</code> 中间件)。</p>
<p>一个中间件接收 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/api#%E4%B8%8A%E4%B8%8B%E6%96%87%E5%AF%B9%E8%B1%A1">context</a> 作为第一个参数：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> (<span class="params">context</span>) </span>&#123;</span><br><span class="line">  context.userAgent = process.server</span><br><span class="line">    ? context.req.headers[<span class="string">&#x27;user-agent&#x27;</span>]</span><br><span class="line">    : navigator.userAgent</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>中间件执行流程顺序：</p>
<ol>
<li><code>nuxt.config.js</code></li>
<li>匹配布局</li>
<li>匹配页面</li>
</ol>
<p>然后在你的 <code>nuxt.config.js</code> 、 layouts 或者 pages 中使用中间件:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// nuxt.config.js</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  <span class="attr">router</span>: &#123;</span><br><span class="line">    <span class="attr">middleware</span>: <span class="string">&#x27;auth&#x27;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在，<code>auth</code> 中间件将在每个路由改变时被调用。</p>
<p>您也可以将 middleware 添加到指定的布局或者页面:</p>
<p><strong>注意</strong>：这里如果在上面的nuxt.config.js里面也添加了中间件的话，这两个中间件都会被调用</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">pages/index.vue<span class="string">` 或者 `</span>layouts/<span class="keyword">default</span>.vue</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">middleware</span>: <span class="string">&#x27;auth&#x27;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<p>还有一些其他的路由，但基本不用就不记录了</p>
<p>最后简单总结一下：</p>
<p>注意一下 <strong>index.vue</strong> 文件，会根据目录自动创建相应路由，</p>
<ul>
<li>普通路由：直接在pages目录里面创建 <strong>a.vue</strong> 文件，会自动生成 <strong>/a</strong> 的路由，也可先创建一个目录，如目录名为<strong>ts</strong>，然后在目录里面创建 <strong>b.vue</strong> 文件，最后产生的路由为 <strong>/ts/b</strong></li>
<li>动态路由：就是在带参数的路由，最主要的就是使用下划线开头命名  <strong>_*.vue</strong> 文件，也可以相似的命名目录，使得下划线开头的目录里面的 <strong>index.vue</strong> 也变成动态的，注意同一个目录里面的动态路由文件只能创建一个，因为url只会匹配到一个动态路由文件</li>
<li>嵌套路由：直接创建一个目录（如 ts），同时创建一个跟目录同名的<strong>ts.vue</strong>文件，在这个文件里面增加 <code>&lt;nuxt-child/&gt;</code> 用于显示子视图内容。然后在创建的目录里面新建 <strong>.vue</strong> 文件即可进行嵌套，生成的路由文件里面，这些目录里的文件就会在 <strong>/ts</strong> 路由的children属性中</li>
</ul>
<h4 id="最后一个示例"><a href="#最后一个示例" class="headerlink" title="最后一个示例"></a>最后一个示例</h4><p>pages目录结构</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">.</span><br><span class="line">├── _slug</span><br><span class="line">│   ├── _e.vue</span><br><span class="line">│   ├── d.vue</span><br><span class="line">│   └── index.vue</span><br><span class="line">├── index.vue</span><br><span class="line">├── test.vue</span><br><span class="line">├── ts</span><br><span class="line">	#这里的两个动态路由文件其实只会根据顺序匹配到_b.vue文件，_c.vue根本无法用到</span><br><span class="line">│   ├── _b.vue</span><br><span class="line">│   ├── _c.vue</span><br><span class="line">│   ├── a.vue</span><br><span class="line">│   └── index.vue</span><br><span class="line">└── ts.vue</span><br></pre></td></tr></table></figure>

<p>生成的路由文件</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 这里的乱码是引入的视图文件的随机名字</span></span><br><span class="line"><span class="attr">routes</span>: [&#123;</span><br><span class="line">    <span class="attr">path</span>: <span class="string">&quot;/test&quot;</span>,</span><br><span class="line">    <span class="attr">component</span>: _1f67911e,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;test&quot;</span></span><br><span class="line">  &#125;, &#123;</span><br><span class="line">    <span class="attr">path</span>: <span class="string">&quot;/ts&quot;</span>,</span><br><span class="line">    <span class="comment">// 这里的组件就是父组件，在这里面添加&lt;/nuxt-child&gt;</span></span><br><span class="line">    <span class="attr">component</span>: _0c0e2ec4,</span><br><span class="line">    <span class="comment">// 这里就是嵌套路由</span></span><br><span class="line">    <span class="attr">children</span>: [&#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&quot;&quot;</span>,</span><br><span class="line">      <span class="comment">// 这里的就是引入的ts目录下的index.vue文件 匹配到localhost:3000/ts</span></span><br><span class="line">      <span class="attr">component</span>: _e203c3b8,</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&quot;ts&quot;</span></span><br><span class="line">    &#125;, &#123;</span><br><span class="line">      <span class="comment">// 匹配到localhost:3000/ts/a</span></span><br><span class="line">      <span class="attr">path</span>: <span class="string">&quot;a&quot;</span>,</span><br><span class="line">      <span class="attr">component</span>: _3ed4f99a,</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&quot;ts-a&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">	<span class="comment">// 根据顺序这里的动态路由只会匹配到_b.vue文件，下面的_c.vue文件根本匹配不到 匹配到localhost:3000/ts/456</span></span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&quot;:b&quot;</span>,</span><br><span class="line">      <span class="attr">component</span>: _316d4381,</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&quot;ts-b&quot;</span></span><br><span class="line">    &#125;, &#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&quot;:c&quot;</span>,</span><br><span class="line">      <span class="attr">component</span>: _317b5b02,</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&quot;ts-c&quot;</span></span><br><span class="line">    &#125;]</span><br><span class="line">  &#125;, &#123;</span><br><span class="line">    <span class="attr">path</span>: <span class="string">&quot;/&quot;</span>,</span><br><span class="line">    <span class="attr">component</span>: _32107203,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;index&quot;</span></span><br><span class="line">  &#125;, &#123;</span><br><span class="line">    <span class="comment">// 这里就相当于直接根目录的动态路由 如 localhost:3000/123 就会匹配到这个路由，似乎可以使用这个来进行404页面的创建</span></span><br><span class="line">    <span class="attr">path</span>: <span class="string">&quot;/:slug&quot;</span>,</span><br><span class="line">    <span class="attr">component</span>: _41ca4b67,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;slug&quot;</span></span><br><span class="line">  &#125;, &#123;</span><br><span class="line">   	<span class="comment">// 匹配到localhost:3000/123/d</span></span><br><span class="line">    <span class="attr">path</span>: <span class="string">&quot;/:slug/d&quot;</span>,</span><br><span class="line">    <span class="attr">component</span>: _1039df0e,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;slug-d&quot;</span></span><br><span class="line">  &#125;, &#123;</span><br><span class="line">    <span class="comment">// 匹配到localhost:3000/123/456</span></span><br><span class="line">    <span class="attr">path</span>: <span class="string">&quot;/:slug/:e&quot;</span>,</span><br><span class="line">    <span class="attr">component</span>: _0245c8be,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;slug-e&quot;</span></span><br><span class="line">  &#125;],</span><br></pre></td></tr></table></figure>





<h3 id="视图"><a href="#视图" class="headerlink" title="视图"></a>视图</h3><p>就是对layout目录里面的<strong>default.vue</strong>文件的操作，这个文件就相当于vue里的App.vue文件，使用 <strong>&lt;Nuxt /&gt;</strong> 将前面的<strong>default.vue</strong>显示出来，也就相当于vue里的 **&lt;router-view /&gt; **  </p>
<h4 id="模板"><a href="#模板" class="headerlink" title="模板"></a>模板</h4><p>定制化默认的 html 模板，只需要在 src 文件夹下（默认是应用根目录）创建一个 <code>app.html</code> 的文件。</p>
<p>默认模板为：</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> &#123;&#123; <span class="attr">HTML_ATTRS</span> &#125;&#125;&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span> &#123;&#123; <span class="attr">HEAD_ATTRS</span> &#125;&#125;&gt;</span></span><br><span class="line">    &#123;&#123; HEAD &#125;&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span> &#123;&#123; <span class="attr">BODY_ATTRS</span> &#125;&#125;&gt;</span></span><br><span class="line">    &#123;&#123; APP &#125;&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>可以在这里改一下网页的图标，title这些东西</p>
<h4 id="布局"><a href="#布局" class="headerlink" title="布局"></a>布局</h4><p>可根据上面的 <strong>default.vue</strong> 文件进行修改，创建一个新的布局文件(如 blog.vue)，然后在一个页面里面使用 <strong>layout:“blog”</strong> 进行使用，虽然感觉没啥用</p>
<h4 id="404页面"><a href="#404页面" class="headerlink" title="404页面"></a>404页面</h4><p>可以在layout目录里面创建一个 <strong>error.vue</strong> 文件（一定要名称为 <strong>error</strong>），在这里面创建404页面</p>
<p><strong>注意</strong>：虽然此文件放在 <code>layouts</code> 文件夹中, 但应该将它看作是一个 <strong>页面(page)</strong>.</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div class=&quot;container&quot;&gt;</span><br><span class="line">    &lt;h1 v-if=&quot;error.statusCode === 404&quot;&gt;页面不存在&lt;/h1&gt;</span><br><span class="line">    &lt;h1 v-else&gt;应用发生错误异常&lt;/h1&gt;</span><br><span class="line">    // 这里的$router是context自带的路由属性</span><br><span class="line">    &lt;button @click=&quot;$router.replace(&#x27;/ts&#x27;)&quot;&gt;跳转到ts页面&lt;/button&gt;</span><br><span class="line">    &lt;nuxt-link to=&quot;/&quot;&gt;首 页&lt;/nuxt-link&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  props: &#123;</span><br><span class="line">    error: &#123;</span><br><span class="line">      type: Object,</span><br><span class="line">      default: null,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;, // 你可以为错误页面指定自定义的布局</span><br><span class="line">&#125;</span><br><span class="line">&lt;/script&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>然后错误的路由都会自动跳转到这个页面</p>
<h4 id="页面"><a href="#页面" class="headerlink" title="页面"></a>页面</h4><p>页面组件实际上是 Vue 组件，只不过 Nuxt.js 为这些组件添加了一些特殊的配置项（对应 Nuxt.js 提供的功能特性）以便你能快速开发通用应用。</p>
<p>Nuxt.js 为页面提供的特殊配置项：</p>
<table>
<thead>
<tr>
<th>属性名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>asyncData</td>
<td>最重要的一个键, 支持 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/guide/async-data">异步数据处理</a>，另外该方法的第一个参数为当前页面组件的 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/api#%E4%B8%8A%E4%B8%8B%E6%96%87%E5%AF%B9%E8%B1%A1">上下文对象</a>。</td>
</tr>
<tr>
<td>fetch</td>
<td>与 <code>asyncData</code> 方法类似，用于在渲染页面之前获取数据填充应用的状态树（store）。不同的是 <code>fetch</code> 方法不会设置组件的数据。详情请参考 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/api/pages-fetch">关于 fetch 方法的文档</a>。</td>
</tr>
<tr>
<td>head</td>
<td>配置当前页面的 Meta 标签, 详情参考 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/api/pages-head">页面头部配置 API</a>。</td>
</tr>
<tr>
<td>layout</td>
<td>指定当前页面使用的布局（<code>layouts</code> 根目录下的布局文件）。详情请参考 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/api/pages-layout">关于 布局 的文档</a>。</td>
</tr>
<tr>
<td>loading</td>
<td>如果设置为<code>false</code>，则阻止页面自动调用<code>this.$nuxt.$loading.finish()</code>和<code>this.$nuxt.$loading.start()</code>,您可以手动控制它,请看<a target="_blank" rel="noopener" href="https://nuxtjs.org/examples/custom-page-loading">例子</a>,仅适用于在 nuxt.config.js 中设置<code>loading</code>的情况下。请参考<a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/api/configuration-loading">API 配置 <code>loading</code> 文档</a>。</td>
</tr>
<tr>
<td>transition</td>
<td>指定页面切换的过渡动效, 详情请参考 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/api/pages-transition">页面过渡动效</a>。</td>
</tr>
<tr>
<td>scrollToTop</td>
<td>布尔值，默认: <code>false</code>。 用于判定渲染页面前是否需要将当前页面滚动至顶部。这个配置用于 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/guide/routing#%E5%B5%8C%E5%A5%97%E8%B7%AF%E7%94%B1">嵌套路由</a>的应用场景。</td>
</tr>
<tr>
<td>validate</td>
<td>校验方法用于校验 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/guide/routing#%E5%8A%A8%E6%80%81%E8%B7%AF%E7%94%B1">动态路由</a>的参数。</td>
</tr>
<tr>
<td>middleware</td>
<td>指定页面的中间件，中间件会在页面渲染之前被调用， 请参考 <a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/guide/routing#%E4%B8%AD%E9%97%B4%E4%BB%B6">路由中间件</a>。</td>
</tr>
</tbody></table>
<h3 id="异步数据"><a href="#异步数据" class="headerlink" title="异步数据"></a>异步数据</h3><p>就是上面的<strong>asyncData</strong> 方法的用处，使得我们可以在设置组件的数据之前能异步获取或处理数据。</p>
<p><code>asyncData</code>方法会在组件（<strong>限于页面组件</strong>）每次加载之前被调用。它可以在服务端或路由更新之前被调用。在这个方法被调用的时候</p>
<p><strong>注意</strong>：由于<code>asyncData</code>方法是在组件 <strong>初始化</strong> 前被调用的，所以在方法内是没有办法通过 <code>this</code> 来引用组件的实例对象。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="keyword">async</span> <span class="function"><span class="title">asyncData</span>(<span class="params">&#123; $axios &#125;</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; data &#125; = <span class="keyword">await</span> $axios.get(<span class="string">&#x27;https://api.chengsong.info&#x27;</span>)</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="attr">info</span>: data &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="function"><span class="title">data</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      <span class="attr">info</span>: &#123;&#125;,</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>asyncData</code> 方法返回的数据在融合 <code>data</code> 方法返回的数据后，一并返回给模板进行展示</p>
<h4 id="上下文对象"><a href="#上下文对象" class="headerlink" title="上下文对象"></a>上下文对象</h4><p>就是<code>asyncData</code>的第一个参数 <strong>context</strong> ，里面获取很多东西，如 req和res对象，动态路由数据，错误处理等</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="title">asyncData</span>(<span class="params">&#123; $axios, params, error &#125;</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;error: &#x27;</span>, error)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;params: &#x27;</span>, params)</span><br><span class="line">    <span class="comment">// 这里的$axios是nuxt创建的时候自动集成的，所以可以在上下文对象里面解构出来，其实也可以使用import的方式导入进行使用</span></span><br><span class="line">    <span class="keyword">const</span> &#123; data &#125; = <span class="keyword">await</span> $axios.get(<span class="string">&#x27;https://api.chengsong.info&#x27;</span>)</span><br><span class="line">    <span class="comment">// return &#123; info: data &#125;</span></span><br><span class="line">    <span class="comment">// 这里是引入的方式</span></span><br><span class="line">    <span class="keyword">return</span> axios.get(<span class="string">`https://my-api/posts/<span class="subst">$&#123;params.id&#125;</span>`</span>)</span><br><span class="line">      .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> &#123; <span class="attr">title</span>: res.data.title &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">      .catch(<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">        error(&#123; <span class="attr">statusCode</span>: <span class="number">404</span>, <span class="attr">message</span>: <span class="string">&#x27;Post not found&#x27;</span> &#125;)</span><br><span class="line">      &#125;)</span><br><span class="line"> &#125;,</span><br></pre></td></tr></table></figure>



<h3 id="插件"><a href="#插件" class="headerlink" title="插件"></a>插件</h3><p>可以在应用中使用第三方模块</p>
<blockquote>
<p>Nuxt.js 允许您在运行 Vue.js 应用程序之前执行 js 插件。这在您需要使用自己的库或第三方模块时特别有用。</p>
</blockquote>
<p>需要注意的是，在任何 Vue 组件的<a target="_blank" rel="noopener" href="https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram">生命周期</a>内， 只有 <code>beforeCreate</code> 和 <code>created</code> 这两个方法会在 <strong>客户端和服务端</strong>被调用。其他生命周期函数仅在客户端被调用。</p>
<p>如 使用<strong>axios</strong></p>
<p>首先我们需要安装 npm 包：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">npm install --save axios</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 然后进行使用</span></span><br><span class="line">&lt;script&gt;</span><br><span class="line">  <span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">&#x27;axios&#x27;</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="keyword">async</span> <span class="function"><span class="title">asyncData</span>(<span class="params">&#123; params &#125;</span>)</span> &#123;</span><br><span class="line">      <span class="keyword">let</span> &#123; data &#125; = <span class="keyword">await</span> axios.get(<span class="string">`https://my-api/posts/<span class="subst">$&#123;params.id&#125;</span>`</span>)</span><br><span class="line">      <span class="keyword">return</span> &#123; <span class="attr">title</span>: data.title &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>



<p>像其他的elment-ui这些都是如此</p>
<p>而且有些还需要在 <code>nuxt.config.js</code> 内配置 <code>plugins</code> 如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  <span class="attr">plugins</span>: [<span class="string">&#x27;@/plugins/element-ui&#x27;</span>]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="注入vue实例"><a href="#注入vue实例" class="headerlink" title="注入vue实例"></a>注入vue实例</h4><p>有时您希望在整个应用程序中使用某个函数或属性值，此时，你需要将它们注入到 Vue 实例（客户端），context（服务器端）甚至 store(Vuex)。按照惯例，新增的属性或方法名使用<code>$</code>作为前缀。</p>
<p>将内容注入 Vue 实例，避免重复引入，在 Vue 原型上挂载注入一个函数，所有组件内都可以访问(<strong>不包含服务器端</strong>)。</p>
<p><code>plugins/vue-inject.js</code>:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"></span><br><span class="line">Vue.prototype.$myInjectedFunction = <span class="function"><span class="params">string</span> =&gt;</span></span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">&#x27;This is an example&#x27;</span>, string)</span><br></pre></td></tr></table></figure>

<p><code>nuxt.config.js</code>:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">plugins</span>: [<span class="string">&#x27;~/plugins/vue-inject.js&#x27;</span>]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样，您就可以在所有 Vue 组件中使用该函数。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="function"><span class="title">mounted</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.$myInjectedFunction(<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="注入-context"><a href="#注入-context" class="headerlink" title="注入 context"></a>注入 context</h4><p>context 注入方式和在其它 vue 应用程序中注入类似。</p>
<p><code>plugins/ctx-inject.js</code>:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> (&#123; app &#125;, inject) =&gt; &#123;</span><br><span class="line">  <span class="comment">// Set the function directly on the context.app object</span></span><br><span class="line">  app.myInjectedFunction = <span class="function"><span class="params">string</span> =&gt;</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Okay, another function&#x27;</span>, string)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>nuxt.config.js</code>:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">plugins</span>: [<span class="string">&#x27;~/plugins/ctx-inject.js&#x27;</span>]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在，只要您获得 context，你就可以使用该函数（例如在<code>asyncData</code>和<code>fetch</code>中）。 <code>ctx-example-component.vue</code>:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="function"><span class="title">asyncData</span>(<span class="params">context</span>)</span> &#123;</span><br><span class="line">    context.app.myInjectedFunction(<span class="string">&#x27;ctx!&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其他的context和store需要时去看下官网即可</p>
<p>而且还能对插件plugins进行配置，让其只在客户端使用这个插件</p>
<h3 id="模块"><a href="#模块" class="headerlink" title="模块"></a>模块</h3><p><em>模块是 Nuxt.js 扩展，可以扩展其核心功能并添加无限的集成</em></p>
<p>Nuxt.js 团队提供 <strong>官方</strong> 模块:</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://http.nuxtjs.org/">@nuxt/http</a>: 基于<a target="_blank" rel="noopener" href="https://github.com/sindresorhus/ky-universal">ky-universal</a>的轻量级和通用的 HTTP 请求</li>
<li><a target="_blank" rel="noopener" href="https://axios.nuxtjs.org/">@nuxtjs/axios</a>: 安全和使用简单 Axios 与 Nuxt.js 集成用来请求 HTTP</li>
<li><a target="_blank" rel="noopener" href="https://pwa.nuxtjs.org/">@nuxtjs/pwa</a>: 使用经过严格测试，更新且稳定的 PWA 解决方案来增强 Nuxt</li>
<li><a target="_blank" rel="noopener" href="https://auth.nuxtjs.org/">@nuxtjs/auth</a>: Nuxt.js 的身份验证模块，提供不同的方案和验证策略</li>
</ul>
<p>需要在nuxt.config.js里面的modules属性里面注册</p>
<h3 id="vuex"><a href="#vuex" class="headerlink" title="vuex"></a>vuex</h3><p>Nuxt.js 会尝试找到 src 目录（默认是应用根目录）下的 <code>store</code> 目录，如果该目录存在，它将做以下的事情：</p>
<ol>
<li>引用 <code>vuex</code> 模块</li>
<li>将 <code>vuex</code> 模块 加到 vendors 构建配置中去</li>
<li>设置 <code>Vue</code> 根实例的 <code>store</code> 配置项</li>
</ol>
<ul>
<li><strong>模块方式：</strong> <code>store</code> 目录下的每个 <code>.js</code> 文件会被转换成为状态树<a target="_blank" rel="noopener" href="http://vuex.vuejs.org/en/modules.html">指定命名的子模块</a> （当然，<code>index</code> 是根模块）</li>
</ul>
<p>具体的使用方式看一下官网介绍即可</p>
<h4 id="fetch方法"><a href="#fetch方法" class="headerlink" title="fetch方法"></a>fetch方法</h4><p><em>fetch 方法用于在渲染页面前填充应用的状态树（store）数据， 与 asyncData 方法类似，不同的是它不会设置组件的数据。</em></p>
<p>如果页面组件设置了 <code>fetch</code> 方法，它会在组件每次加载前被调用（在服务端或切换至目标路由之前）</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;h1&gt;Stars: &#123;&#123; $store.state.stars &#125;&#125;&lt;/h1&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line">  export default &#123;</span><br><span class="line">    async fetch(&#123; store, params &#125;) &#123;</span><br><span class="line">      let &#123; data &#125; = await axios.get(&#x27;http://my-api/stars&#x27;)</span><br><span class="line">      store.commit(&#x27;setStars&#x27;, data)</span><br><span class="line">      await store.dispatch(&#x27;GET_STARS&#x27;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>







<h4 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h4><h3 id="其他-1"><a href="#其他-1" class="headerlink" title="其他"></a>其他</h3><p><code>nuxt start </code> 执行后的端口号是在nuxt项目在package.json里面进行修改的）</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="string">&quot;name&quot;</span>: <span class="string">&quot;firstStudy&quot;</span>,</span><br><span class="line">  <span class="string">&quot;version&quot;</span>: <span class="string">&quot;1.0.0&quot;</span>,</span><br><span class="line">  <span class="string">&quot;private&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="string">&quot;scripts&quot;</span>: &#123;</span><br><span class="line">    <span class="string">&quot;dev&quot;</span>: <span class="string">&quot;nuxt&quot;</span>,</span><br><span class="line">    <span class="string">&quot;build&quot;</span>: <span class="string">&quot;nuxt build&quot;</span>,</span><br><span class="line">    <span class="string">&quot;start&quot;</span>: <span class="string">&quot;PORT=3003 nuxt start&quot;</span>, <span class="comment">//注意这里的port，在部署的时候会运行在这个端口上，主要是为了防止服务器端口冲突</span></span><br><span class="line">    <span class="string">&quot;generate&quot;</span>: <span class="string">&quot;nuxt generate&quot;</span>,</span><br><span class="line">    <span class="string">&quot;lint:js&quot;</span>: <span class="string">&quot;eslint --ext \&quot;.js,.vue\&quot; --ignore-path .gitignore .&quot;</span>,</span><br><span class="line">    <span class="string">&quot;lint&quot;</span>: <span class="string">&quot;yarn lint:js&quot;</span></span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure>

<p><code>nuxt</code> 执行后的端口号是在  <strong>nuxt.config.js</strong> 文件里面修改的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span>&#123;</span><br><span class="line">    <span class="attr">server</span>: &#123;    </span><br><span class="line">        <span class="attr">port</span>: <span class="number">8000</span>,     <span class="comment">// default: 3000</span></span><br><span class="line">        <span class="comment">// host: &#x27;0.0.0.0&#x27; // default: localhost</span></span><br><span class="line">     &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>nuxt项目似乎对scss有针对的集成，但对less就有些问题，我使用的时候就会出现错误，所以还是使用scss吧</p>
<p>nuxt项目在使用官方的npx创建的时候如果选择了axios就会自动引入这个模块，之后就能在context上下文对象里面获取到</p>
<p><a target="_blank" rel="noopener" href="https://axios.nuxtjs.org/usage/">官方axios集成</a> </p>
<p>nuxt大部分的情况下就是约定式的，就是你按照一定的规范这样做，nuxt自己会根据你做的东西生成对应的代码，比如在layout布局里面的 <strong>error.vue</strong> 文件就会被当成一个404页面，注意名称一定要是error.vue，且在layout目录下</p>
<h4 id="命令"><a href="#命令" class="headerlink" title="命令"></a>命令</h4><p>官方网址：<a target="_blank" rel="noopener" href="https://www.nuxtjs.cn/guide/commands">https://www.nuxtjs.cn/guide/commands</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2021/01/31/Nuxtjs初学习/">https://chengsong.info/2021/01/31/Nuxtjs初学习/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/vue-nuxtjs/">vue nuxtjs</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2021/02/05/Nodejs-express-koa2%E5%88%9D%E5%AD%A6%E4%B9%A0/"><i class="fa fa-chevron-left">  </i><span>Nodejs express koa2初学习</span></a></div><div class="next-post pull-right"><a href="/2021/01/21/js%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E6%8C%87%E5%8D%97%E7%AC%AC%E5%9B%9B%E7%89%88-%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/"><span>js高级程序指南第四版--学习记录</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>